﻿using System;
using System.Collections.Generic;

namespace Development.Network.Tcp
{
    public class TcpTokenManager
    {
        private readonly object _flagLock = new object();
        protected SortedDictionary<int, TcpToken> _manager = new SortedDictionary<int, TcpToken>();
        protected Queue<TcpToken> _pool = new Queue<TcpToken>();     //对象池

        /// <summary>
        /// 放入一个对象
        /// </summary>
        /// <param name="item"></param>
        public void Push(TcpToken item)
        {
            if (item == null)
            {
                throw new ArgumentException("ObjectPool Items added  cannot be null");
            }
            lock (_flagLock)
            {
                _pool.Enqueue(item);
                _manager.Remove(item.LinkId);
            }
        }

        /// <summary>
        /// 获取一个对象
        /// </summary>
        /// <returns></returns>
        public TcpToken Pop()
        {
            TcpToken item = null;
            lock (_flagLock)
            {
                if (_pool.Count != 0)
                {
                    item = _pool.Dequeue();
                    _manager.Add(item.LinkId, item);
                }
            }
            return item;
        }

        public List<TcpToken> GetList()
        {
            lock (_flagLock)
            {
                return new List<TcpToken>(_manager.Values);
            }
        }

        public TcpToken GetUserToken(int linkId)
        {
            TcpToken token = null;
            lock (_flagLock)
            {
                _manager.TryGetValue(linkId, out token);
            }
            return token;
        }

        public int Count()
        {
            lock (_flagLock)
            {
                return _manager.Count;
            }
        }
    }
}
